package cn.itsource.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.itsource.domain.Employee;
import cn.itsource.domain.Login;
import cn.itsource.domain.Tenant;
import cn.itsource.dto.LoginMealDto;
import cn.itsource.dto.RegisterDto;
import cn.itsource.exception.MyException;
import cn.itsource.feign.client.LoginFeignClient;
import cn.itsource.mapper.EmployeeMapper;
import cn.itsource.mapper.TenantMapper;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bobo
 * @since 2022-11-08
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginFeignClient loginFeignClient;

    /**
     * 机构注册
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional //处理分布式事务
    public JSONResult register(RegisterDto dto) {
        /**
         * 1、数据保存到两个库，分别4张表中
         */

        //保存员工信息入库
        Employee employee = dto.getEmployee();
        employeeMapper.insert(employee);

        //保存机构信息入库
        Tenant tenant = dto.getTenant();
        tenant.setAdminId(employee.getId());
        tenantMapper.insert(tenant);

        //账号登录信息存入Auth数据库中
        Login login = new Login();
        login.setUsername(dto.getUsername());
        login.setPassword(SecureUtil.md5(dto.getPassword()));//加密
        JSONResult retsult = loginFeignClient.save(login);
        if(!retsult.isSuccess()){
            //保存信息到t_login表失败
            throw new MyException(retsult.getMessage());
        }

        Integer loginIdString = (Integer)retsult.getData();
        Long loginId = Long.valueOf(loginIdString);

        employee.setTenantId(tenant.getId());
        employee.setLoginId(loginId);//没值
        employeeMapper.updateById(employee);//修改

        //得到t_login表最新的主键ID
        LoginMealDto loginMealDto = new LoginMealDto();
        loginMealDto.setMealId(dto.getMealId());
        loginMealDto.setLoginId(loginId);
        loginMealDto.setExpireDate(DateUtils.addDays(new Date(), 7));//试用期：7天
        JSONResult jsonResult = loginFeignClient.saveLoginMeal(loginMealDto);
        if(!jsonResult.isSuccess()){
            //保存信息到t_login表失败
            return JSONResult.error(jsonResult.getMessage());
        }
        return JSONResult.success();
    }
}